package com.book.shop.Webservice;

import com.book.shop.model.User;
import com.book.shop.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final User user = userRepository.findOneWithRolesByUserName(username);
        if(user ==null){
            System.out.println("error happen and user is null:");
            throw new UsernameNotFoundException(username);
        }
        List<GrantedAuthority> roles = user.getRoles().stream()
                .map(authority ->new SimpleGrantedAuthority(authority.getRolename()))
                .collect(Collectors.toList());
        return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getUserPassword(),roles);
    }
}
